package com.sunday.common.core.remoting.rest.response;

import com.sunday.common.core.constants.LogConstants;
import com.sunday.common.core.constants.StringConstants;
import com.sunday.common.core.enums.ErrorCodeEnum;
import com.sunday.common.core.exception.CoreException;
import com.sunday.common.core.remoting.rest.annotation.VoErrorShowType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;

/**
 * web 响应异常处理
 *
 * @author zsy
 * @since 2022/10/14
 */
@Slf4j
public class RestExceptionResponse {

    public static <T> RestResponse<T> returnResponse(Throwable cause) {
        return returnResponse(cause, (RestResponse.ShowTypeEnum) null);
    }

    public static <T> RestResponse<T> returnResponse(Throwable cause, @Nullable VoErrorShowType voErrorShowType) {
        return returnResponse(cause, voErrorShowType == null ? null : voErrorShowType.value());
    }

    public static <T> RestResponse<T> returnResponse(Throwable cause, @Nullable RestResponse.ShowTypeEnum showTypeEnum) {
        if (cause instanceof CoreException exception) {
            RestResponse response = RestResponse.resultReturn(
                    Boolean.FALSE,
                    exception.getCode(),
                    exception.getMessage(),
                    showTypeEnum,
                    null);
            log.info(LogConstants.response_format_nack, response, StringConstants.EMPTY);
            return response;
        }

        RestResponse response = RestResponse.error(ErrorCodeEnum.B0_001, RestResponse.ShowTypeEnum.NOTIFICATION);
        log.error(LogConstants.response_format_nack, response, cause.toString(), cause);
        return response;
    }

}
